package com.ayla.demo.widgets.extend

import android.view.MotionEvent
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2

fun ViewPager2.fixHorizontalScroll() {
    val recyclerView = getChildAt(0) as RecyclerView
    val touchSlopField = recyclerView::class.java.superclass
        .getDeclaredField("mTouchSlop").also { it.isAccessible = true }

    val originTouchSlop = touchSlopField.get(recyclerView) as Int

    recyclerView.addOnItemTouchListener(object : RecyclerView.OnItemTouchListener {
        private var initialX = -1F
        override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
            when (e.action) {
                MotionEvent.ACTION_DOWN -> {
                    //恢复mTouchSlop
                    touchSlopField.set(recyclerView, originTouchSlop)
                    initialX = e.x
                }
                MotionEvent.ACTION_MOVE -> {
                    val dx = e.x - initialX
                    if ((dx < 0 && !recyclerView.canScrollHorizontally(1)) ||
                        (dx > 0 && !recyclerView.canScrollHorizontally(-1))
                    ) {
                        //👇ViewPager2滑动到边缘，将mTouchSlop设置为最大
                        touchSlopField.set(recyclerView, Integer.MAX_VALUE)
                    }
                }
            }
            return false
        }

        override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {

        }

        override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
            //恢复mTouchSlop
            touchSlopField.set(recyclerView, originTouchSlop)
        }
    })
}
